<?php

/**
 * 同步登录到DZ
 * File Name：TongbuDz.php
 * File Encoding：UTF-8
 * File New Time：2014-9-4 14:57:40
 * Author：水平凡
 * Mailbox：admin@abc3210.com
 */
class TongbuDz {

    //通知地址
    protected $jsUrl = '';
    //标识符
    protected $key = '__tongbu__';

    /**
     * 链接同步服务
     * @staticvar null $handier
     * @return \TongbuDz
     */
    static public function getInstance() {
        static $handier = NULL;
        if (empty($handier)) {
            $handier = new TongbuDz();
        }
        return $handier;
    }

    /**
     * 同步登录dz
     * @param type $user 用户信息
     * @return boolean
     */
    public function login($user) {
        if (is_object($user)) {
            $user = $user->attributes;
        }
        if (empty($user)) {
            return false;
        }
        $data = array(
            'username' => $user['username'],
            'email' => $user['email'],
            'password' => $user['expresslyPassword'], //明文密码
        );
        //统一 sign
        $sign = Encrypt::authcode(json_encode($data), '', Yii::app()->params['bbsInfo']['key']);
        $sign = urlencode($sign);
        $this->jsUrl = "yzw_login.php?sign={$sign}";
        return $this->setTongbuJS();
    }

    /**
     * 同步退出DZ
     * @return boolean
     */
    public function logout() {
        $this->jsUrl = "yzw_logout.php";
        return $this->setTongbuJS();
    }

    /**
     * 设置同步处理
     * @return type
     */
    public function setTongbuJS() {
        if (empty($this->jsUrl)) {
            return false;
        }
        $js = '<script type="text/javascript" src="' . Yii::app()->params['bbsInfo']['url'] . $this->jsUrl . '"></script>';
        return Yii::app()->session->add($this->key, $js);
    }

    /**
     * 执行同步
     */
    public function sendTongbu() {
        $tongbu = Yii::app()->session[$this->key];
        Yii::app()->session->remove($this->key);
        if (!empty($tongbu)) {
            return $tongbu;
        }
        return '';
    }

}
